Ext.define('manager.user', {
    extend: 'Ext.Panel',
    layout: 'border',
    initComponent: function () {
        var _this = this;
        var grid;
        var keywordsField = Ext.create('Ext.form.field.Text', {
            name: 'keywords',
            xtype: 'textfield',
            emptyText: '姓名'
        });

        // 工具栏
        this.tbar = [
            {
                text: '添加',
                icon: F.url("/resources/icons/16/add.png"),
                handler: function () {
                    _this.showAddWindow();
                }
            },
            {
                text: '编辑',
                icon: F.url("/resources/icons/16/application_edit.png"),
                handler: function () {
                    if (grid.getSelectionModel().hasSelection()) {
                        var record = grid.getStore().getById(grid.getSelectionModel().getSelection()[0].getId());
                        _this.showEditWindow(record);
                    }
                }
            },
            '-',
            {

                text: '授权',
                icon: F.url("/resources/icons/16/application_delete.png"),
                handler: function () {
                    if (grid.getSelectionModel().hasSelection()) {
                        var record = grid.getStore().getById(grid.getSelectionModel().getSelection()[0].getId());

                        _this.showGrantWindow(record);
                    }
                }
            },
            '->',
            {
                text: '启用',
                icon: F.url("/resources/icons/16/accept.png"),
                handler: function () {
                    if (grid.getSelectionModel().hasSelection()) {
                        var record = grid.getStore().getById(grid.getSelectionModel().getSelection()[0].getId());
                        Ext.Ajax.request({
                            url: F.url("/admin/adminUser/enable.do"),
                            params: {
                                userId: record.get('userId')
                            },
                            success: function (response) {
                                var text = response.responseText;
                                var result = Ext.JSON.decode(text);
                                if (result.success) {
                                    grid.getStore().reload();
                                    UI.showSuccessMsg("用户启用操作成功");
                                } else {
                                    UI.showErrorMsg("用户启用操作失败", result.error || "请重试");
                                }
                            },
                            failure: function (response, opts) {
                                UI.showErrorMsg("用户启用操作失败", "内部错误");
                            }
                        });
                    }
                }
            },
            {
                text: '停用',
                icon: F.url("/resources/icons/16/cancel.png"),
                handler: function () {
                    if (grid.getSelectionModel().hasSelection()) {
                        var record = grid.getStore().getById(grid.getSelectionModel().getSelection()[0].getId());
                        Ext.Ajax.request({
                            url: F.url("/admin/adminUser/disable.do"),
                            params: {
                                userId: record.get('userId')
                            },
                            success: function (response) {
                                var text = response.responseText;
                                var result = Ext.JSON.decode(text);
                                if (result.success) {
                                    grid.getStore().reload();
                                    UI.showSuccessMsg("用户停用操作成功");
                                } else {
                                    UI.showErrorMsg("用户停用操作失败", result.error || "请重试");
                                }
                            },
                            failure: function (response, opts) {
                                UI.showErrorMsg("用户停用操作失败", "内部错误");
                            }
                        });
                    }
                }
            },
//            {
//                disabled: true,
//                text: '删除',
//                icon: F.url("/resources/icons/16/delete.png"),
//                handler: function () {
//                    if (grid.getSelectionModel().hasSelection()) {
//                        var record = grid.getStore().getById(grid.getSelectionModel().getSelection()[0].getId());
//                        Ext.Msg.confirm('严重', "！！！删除用户，是否继续？", function (b) {
//                            if (b != 'yes') {
//                                return;
//                            }
//                            Ext.Ajax.request({
//                                url: F.url("/admin/adminUser/remove.do"),
//                                params: {
//                                    userId: record.get('userId')
//                                },
//                                success: function (response) {
//                                    var text = response.responseText;
//                                    var result = Ext.JSON.decode(text);
//                                    if (result.success) {
//                                        grid.getStore().reload();
//                                        UI.showSuccessMsg("用户删除操作成功");
//                                    } else {
//                                        UI.showErrorMsg("删除失败", result.msg || "请重试");
//                                    }
//                                },
//                                failure: function (response, opts) {
//                                    UI.showErrorMsg("删除失败", "内部错误");
//                                }
//                            });
//                        });
//                    }
//                }
//            },

            '-',
            keywordsField,
            {
                text: '搜索',
                icon: F.url("/resources/icons/16/find.png"),
                pressed: true,
                handler: function () {
                    if (keywordsField.getValue()) {
                        _this.setTitle("用户管理 - 搜索  " + keywordsField.getValue());
                    } else {
                        _this.setTitle("用户管理");
                    }
                    delete store.getProxy().extraParams.usertype;
                    grid.getStore().load({
                        params: {
                            keywords: keywordsField.getValue()
                        }
                    });
                }
            }
        ];

        var fields = [ 'userId', 'email', 'realName', "nickname", "userType", "openId", "phone", "gender", 'superman', "lastLoginIp", 'status', {
            name: 'createdAt',
            type: 'date',
            dateFormat: 'time'
        }, "createdByUserId", "createdByRealName"];
        var columns = [
            {
                xtype: 'rownumberer'
            },
            {
                text: '帐号',
                dataIndex: 'email',
                width: 200,
                renderer: function (v, m, r) {
                    if (r.get('superman') == 1) {
                        m.style = "color:blue";
                    }
                    return v;
                }
            },
            {
                text: '真实姓名',
                dataIndex: 'realName'
            },
            {
                text: "昵称",
                dataIndex: "nickname"
            },
            {
                text: "用户类型",
                dataIndex: "userType",
                renderer: function (v, m, r) {
                    if (v == 1) {
                        return "系统管理员";
                    } else if (v == 3) {
                        return "自媒体用户";
                    } else if (v == 2) {
                        return "广告主用户";
                    } else if (v == 4) {
                        return "蓝标用户";
                    }
                }
            },
            {
                text: "绑定微信",
                dataIndex: "openId",
                width: 150,
                renderer: function (v) {
                    if (v) {
                        return '是'
                    } else {
                        return ''
                    }
                }
            },
            {
                text: "联系电话",
                dataIndex: "phone",
                width: 150
            },
            {
                text: "性别",
                dataIndex: "gender",
                renderer: function (v) {
                    if (v == 'M') {
                        return '男';
                    } else {
                        return '女';
                    }
                }
            },
            {
                text: "最后一次登录IP",
                dataIndex: "lastLoginIp",
                width: 150
            },
            {
                text: '状态',
                dataIndex: 'status',
                renderer: function (v) {
                    if (v == 1) {
                        return '可用';
                    } else {
                        return '不可用';
                    }
                }
            },
            {
                text: '创建时间',
                dataIndex: 'createdAt',
                renderer: Ext.util.Format.dateRenderer('Y-m-d')
            }

        ];
        var store = Ext.create('Ext.data.Store', {
            storeId: 'userStore',
            pageSize: 50,
            proxy: {
                type: 'ajax',
                url: F.url('/admin/adminUser/list.do'),
//                method: 'post',
                actionMethods: {read: 'POST'},
                reader: {
                    type: 'json',
                    root: 'pageList.list',
                    idProperty: 'userId',
                    totalProperty: 'pageList.page.total',
                    messageProperty: "msg"
                }
            },
            // alternatively, a Ext.data.Model name can be given (see Ext.data.Store
            // for an example)
            fields: fields
        });

        // 列表
        grid = Ext.create('Ext.grid.Panel', {
            dockedItems: [
                {
                    xtype: 'pagingtoolbar',
                    store: store, // same store GridPanel is using
                    dock: 'bottom',
                    displayInfo: true
                }
            ],
            forceFit: true,
            itemId: 'grid',
            region: 'center',
            store: store,
            columns: columns,
            listeners: {
                render: function () {
                    store.load();

                },
                itemdblclick: function (g, record, item, index, e, eOpts) {
                    _this.showEditWindow(record);
                }
            }
        });
        _this.items = [ grid ];
        this.callParent();
    },
    // 弹出添加窗口
    showAddWindow: function () {
        var _this = this;

        Ext.create('manager.user.FormWindow', {
            title: '创建用户账号',
            formUrl: F.url('/admin/adminUser/add.do'),
            submitSuccessCallback: function (win) {
                win.close();
                UI.showSuccessMsg("用户创建成功");
                _this.getComponent('grid').getStore().reload();
            }
        }).show();
    },
    // 弹出修改窗口
    showEditWindow: function (rec) {
        var _this = this;

        Ext.create('manager.user.FormWindow', {
            title: '编辑用户' + rec.get('realName') + '资料',
            formUrl: F.url('/admin/adminUser/update.do'),
            user: rec,
            submitSuccessCallback: function (win) {
                win.close();
                UI.showSuccessMsg("用户资料修改成功");
                _this.getComponent('grid').getStore().reload();
            }
        }).show();
    },

    showGrantWindow: function (rec) {
        var _this = this;
        Ext.create('manager.user.GrantWindow', {
            title: '给用户' + rec.get('realName') + '授权',
            formUrl: F.url('/admin/adminUser/grant.do'),
            user: rec,
            submitSuccessCallback: function (win) {
                win.close();
                UI.showSuccessMsg("权限修改成功");
                _this.getComponent('grid').getStore().reload();
            }
        }).show();
    }
});
// 用户授权表单窗口

Ext.define('manager.user.GrantWindow', {
    extend: 'Ext.window.Window',
    height: 600,
    width: 800,
    layout: 'border',
    modal: true,
    initComponent: function () {
        var win = this;
        Ext.apply(this, {
            buttons: [
                {
                    text: '确认',
                    scope: this,
                    handler: function () {
                        win.getComponent('form').submit({
                            clientValidation: true,
                            success: function (form, action) {
                                if (win.submitSuccessCallback) {
                                    win.submitSuccessCallback(win);
                                } else {
                                    win.close();
                                }
                            },
                            failure: function (form, action) {
                                if (win.submitFailureCallback) {
                                    win.submitFailureCallback(win);
                                } else {
                                    switch (action.failureType) {
                                        case Ext.form.action.Action.CLIENT_INVALID:
                                            UI.showErrorMsg('失败', '请检查输入的内容是否完整并且无误');
                                            break;
                                        case Ext.form.action.Action.CONNECT_FAILURE:
                                            UI.showErrorMsg('失败', '请求超时，请检查网络是否正常');
                                            break;
                                        case Ext.form.action.Action.SERVER_INVALID:
                                            UI.showErrorMsg('失败', action.result.error);
                                    }
                                }
                            }
                        });
                    }
                }
            ]
        });

        var fields = [ 'roleId', 'roleName', {
            name: 'description',
            type: 'string'
        } ];

        var form = Ext.create("Ext.form.Panel", {
            itemId: 'form',
            region: 'center',
            bodyPadding: 5,
            url: this.formUrl,
            layout: 'anchor',
            defaults: {
                anchor: '100%'
            },
            // The fields
            defaultType: 'textfield',
            items: [
                {
                    xtype: 'hiddenfield',
                    name: 'userId'
                },
                {
                    fieldLabel: '用户名称',
                    name: 'realName',
                    readOnly: true,
                    editable: false
                },
                {
                    itemId: 'roleCheckboxGroup',
                    xtype: 'checkboxgroup',
                    fieldLabel: '角色',
                    // Arrange checkboxes into two columns, distributed vertically
                    columns: 4,
                    vertical: true,
                    items: []
                }
            ]
        });
        this.items = [ form ];
        this.callParent();
        if (this.user) {
            form.loadRecord(this.user);
            //查询用户角色并选中已有角色

            this.loadUserRoles(this.user.get('userId'));
        }
    },
    loadUserRoles: function (userId) {
        var checkboxGroup = this.getComponent('form').getComponent('roleCheckboxGroup');
        Ext.Ajax.request({
            url: F.url('/admin/adminUser/roleList.do'),
            params: {
                userId: userId
            },
            success: function (response, opts) {
                var obj = Ext.decode(response.responseText);
                if (obj.success) {

                    for (var i = 0; i < obj.list.length; i++) {
                        var role = obj.list[i];
                        checkboxGroup.add({
                            boxLabel: role.roleName,
                            name: 'roleId',
                            inputValue: role.roleId,
                            checked: role.checked
                        });
                    }
                    checkboxGroup.doLayout();
                }
            },
            failure: function (response, opts) {
                console.log('server-side failure with status code ' + response.status);
            }
        });
    }
});

// 用户Form表单窗口

Ext.define('manager.user.FormWindow', {
    extend: 'Ext.window.Window',
    height: 600,
    width: 800,
    layout: 'border',
    modal: true,
    initComponent: function () {
        var win = this;
        Ext.apply(this, {
            buttons: [
                {
                    text: '确认',
                    scope: this,
                    handler: function () {
                        if (!win.user) {
                            var password = win.getComponent('form').getForm().findField('password').getValue();
                            if (!password) {
                                UI.showErrorMsg("创建用户请设置密码");
                                return false;
                            }
                        }
                        win.getComponent('form').submit({
                            clientValidation: true,
                            success: function (form, action) {
                                if (win.submitSuccessCallback) {
                                    win.submitSuccessCallback(win);
                                } else {
                                    win.close();
                                }
                            },
                            failure: function (form, action) {
                                if (win.submitFailureCallback) {
                                    win.submitFailureCallback(win);
                                } else {
                                    switch (action.failureType) {
                                        case Ext.form.action.Action.CLIENT_INVALID:
                                            UI.showErrorMsg('失败', '请检查输入的内容是否完整并且无误');
                                            break;
                                        case Ext.form.action.Action.CONNECT_FAILURE:
                                            UI.showErrorMsg('失败', '请求超时，请检查网络是否正常');
                                            break;
                                        case Ext.form.action.Action.SERVER_INVALID:
                                            UI.showErrorMsg('失败', action.result.msg);
                                    }
                                }
                            }
                        });
                    }
                },
                {
                    text: '取消',
                    scope: this,
                    handler: function () {
                        win.close();
                    }
                }
            ]
        });

        var states = Ext.create("Ext.data.Store", {
            fields: ["id", "name"],
            data: [
                {"id": 1, "name": "是"},
                {"id": 0, "name": "否"}
            ]
        });


        var form = Ext.create("Ext.form.Panel", {
            itemId: 'form',
            region: 'center',
            bodyPadding: 5,
            url: this.formUrl,
            layout: 'anchor',
            defaults: {
                anchor: '100%'
            },
            // The fields
            defaultType: 'textfield',
            items: [
                {
                    xtype: 'hiddenfield',
                    name: 'userId'
                },
                {
                    xtype: 'hiddenfield',
                    name: 'createdByUserId'
                },
                {
                    xtype: 'hiddenfield',
                    name: 'createdByRealName'
                },
                {
                    fieldLabel: '登录帐号（email）',
                    name: 'email',
                    allowBlank: false,
                    emptyText: '请输入email',
                    blankText: '登录账号不能为空',
                    readOnly: win.user ? true : false,
                    vtype: 'email'
                },
                {
                    fieldLabel: '姓名',
                    name: 'realName',
                    allowBlank: false
                },
                {
                    fieldLabel: "昵称",
                    name: "nickname",
                    allowBlank: false
                },
                {
                    fieldLabel: '状态',
                    allowBlank: false,
                    xtype: 'radiogroup',
                    columns: 2,
                    vertical: false,
                    value: '1',
                    items: [
                        { boxLabel: '可用', name: 'status', inputValue: '1', checked: true },
                        { boxLabel: '不可用', name: 'status', inputValue: '0' }
                    ]
                },
                {
                    fieldLabel: '性别',
                    allowBlank: false,
                    xtype: 'radiogroup',
                    columns: 2,
                    vertical: false,
                    items: [
                        { boxLabel: '男', name: 'gender', inputValue: 'M', checked: true },
                        { boxLabel: '女', name: 'gender', inputValue: 'F' }
                    ]
                },
                {
                    fieldLabel: "微信绑定",
                    name: 'openId',
                    xtype: 'displayfield',
                    renderer: function (v) {
                        if (v) {
                            return v;
                        } else {
                            return '未绑定';
                        }
                    }
                },
                {
                    fieldLabel: "电话号码",
                    name: "phone",
                    minLength: 7,
                    maxLength: 12
                },

                {
                    fieldLabel: "最后一次登录IP",
                    name: "lastLoginIp",
                    xtype: 'displayfield'
                },
                {
                    fieldLabel: "创建时间",
                    xtype: "displayfield",
                    name: "createdAt",
                    readOnly: true,
                    renderer: function (v) {
                        return Ext.Date.format(v, 'Y-m-d H:i:s')
                    }
                },
                {
                    xtype: 'fieldset',
                    title: win.user ? '修改密码(不填写表示不修改)' : '设置密码',
                    defaultType: 'textfield',
                    defaults: {
                        anchor: '100%'
                    },
                    layout: 'anchor',
                    items: [
                        {
                            fieldLabel: '密码',
                            name: 'password',
                            inputType: 'password',

                            vtype: 'alphanum',
                            minLength: 6,
                            minLengthText: '密码最短为{0}位',
                            maxLength: 32,
                            maxLengthText: '密码最长不可超过 {0}位'
                        },
                        {
                            fieldLabel: '确认密码',
                            inputType: 'password',

                            vtype: 'alphanum',
                            name: 'confirmPassword',
                            minLength: 6,
                            minLengthText: '密码最短为{0}位',
                            maxLength: 32,
                            maxLengthText: '密码最长不可超过 {0}位'
                        }
                    ]
                }
            ],
            listeners: {
                beforeaction: function (form, action) {
                    if (form.findField('password').getValue() !== form.findField('confirmPassword').getValue()) {
                        UI.showErrorMsg("提示", "两次密码输入不一致");
                        return false;
                    }
                }
            }
        });
        this.items = [ form ];
        this.callParent();
        if (this.user) {
            form.loadRecord(this.user);
        }
    }
});